package com.haopt.elasticjob.config;

import com.dangdang.ddframe.job.lite.api.strategy.JobInstance;
import com.dangdang.ddframe.job.lite.api.strategy.JobShardingStrategy;

import java.util.*;

/**
 * @author haopt
 * @version 1.0
 * @ClassName MyJobShardingStrategy
 * @Description 自定义分片规则
 * @date 2021/5/13 22:27
 */
public class MyJobShardingStrategy implements JobShardingStrategy {

    /**
     * @param jobInstances       服务列表
     * @param jobName            定时任务名称
     * @param shardingTotalCount 总分片数
     * @return
     */
    @Override
    public Map<JobInstance, List<Integer>> sharding(List<JobInstance> jobInstances,
                                                    String jobName,
                                                    int shardingTotalCount) {
        if (jobInstances.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<JobInstance, List<Integer>> map = new HashMap<JobInstance, List<Integer>>();
        //1.生成分片项的列表
        Queue<Integer> queue = new ArrayDeque<Integer>();
        for (int i = 0; i < shardingTotalCount; i++) {
            //0  1  2 3 4 5 6 7 8 9
            queue.add(i);
        }
        //1.迭代服务列表
        for (int i = 0; i < jobInstances.size(); i++) {
            //获取服务
            JobInstance jobInstance = jobInstances.get(i);
            //获取该服务对应的分片项；
            List<Integer> shardingItemList = getShardingItemList(i, jobInstances.size(), queue);
            map.put(jobInstance, shardingItemList);
        }
        return map;
    }

    /**
     * 返回分片列表
     * @param jobInstanceIndex 当前服务的index
     * @param size 服务个数
     * @param queue 所有分片
     * @return
     */
    private List<Integer> getShardingItemList(int jobInstanceIndex, int size, Queue<Integer> queue) {
        //定义jobInstanceIndex 对应的分片列表
        List<Integer> shardingItemList = new ArrayList<Integer>();
        for (int shardingItem : queue) {
            if (shardingItem % size == jobInstanceIndex) {
                shardingItemList.add(shardingItem);
            }
        }
        return shardingItemList;
    }
}
